<template>
  <div class="chartBox" :id="id"></div>
</template>
<script setup name="LineChart">
import * as echarts from "echarts"
import { defineProps, onMounted } from 'vue';
import Colors from "@/config/Colors";
const props = defineProps({
  id: {
    type: String,
    required: true,
    default: 'lineChart'
  },
  option: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
let option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '2%',
    right: '5%',
    bottom: '5%',
    top: '15%',
    containLabel: true,
  },
  legend: {
    top: '5%'
  },
  textStyle: {
    color: "#128075"
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: []
};
onMounted(() => {
  let options = replaceObjectValues(option, props.option)
  initChart(options)
})
function initChart(options) {
  let chart = echarts.init(
      document.getElementById(props.id),
      "chalk"
  );
  // 监听屏幕变化自动缩放图表
  let chartMain = document.querySelector('.chartBox')
  new ResizeObserver(entries => {
    chart.resize();
  }).observe(chartMain);
  chartMain.addEventListener("resize", function () {
    chart.resize();
  })
  chart.setOption(options);
}
/**
 * 深度递归替换对象中的属性值
 * @param {Object} target - 原始对象
 * @param {Object} replacement - 用于替换的对象
 */
function replaceObjectValues(target, replacement) {
  if (Array.isArray(target) && Array.isArray(replacement)) {
    // 如果 target 和 replacement 都是数组，直接覆盖整个数组
    for (let i = 0; i < replacement.length; i++) {
      if (i < target.length && typeof target[i] === "object" && target[i] !== null) {
        // 如果数组项是对象，递归处理
        replaceObjectValues(target[i], replacement[i]);
      } else {
        // 如果不是对象或索引超出范围，直接替换
        target[i] = replacement[i];
      }
    }
    // 如果 replacement 数组比 target 长，追加新项
    if (replacement.length > target.length) {
      target.splice(target.length, 0, ...replacement.slice(target.length));
    }
  } else if (typeof target === "object" && target !== null && typeof replacement === "object" && replacement !== null) {
    for (let key in replacement) {
      if (replacement.hasOwnProperty(key)) {
        if (key in target) {
          if (typeof target[key] === "object" && target[key] !== null) {
            // 如果值是对象或数组，递归处理
            replaceObjectValues(target[key], replacement[key]);
          } else {
            // 如果是普通值，直接替换
            target[key] = replacement[key];
          }
        }
      }
    }
  }
  return target;
}
</script>
<style lang="scss" scoped>
.chartBox{
  width: 100%;
  height: 100%;
}
</style>